

local app = require "app"
local gamelib = require "club.threecard.gamelib"
local slotlib = require "club.threecard.slotlib"
local game = app.game.running

local M = gamelib.ui.element()

local Matcher = gamelib.entitas.Matcher
local components = slotlib.components

local default_res = "club.threecard.slotlib/ui/common.b:spin_button"

M.store_watchers = {
    machine = 
    {
        ["改变下注状态"] = function(self, store, state)
            group = self.context:get_group(Matcher({components.auto_component}))
            group.entities:foreach(function(e)
                local c = e:get(components.auto_component)
                c.is_auto = state.auto
            end)

            self.btn_stop_auto.gameObject:SetActive(state.auto)
            self.btn_launch.gameObject:SetActive(not state.auto)
        end
    }
}

function M:ctor(context, systems, res)
    self.res = res or default_res
    self.press_auto_unbind = nil
    self.context = context
    self.systems = systems
end

function M:on_injected(bind)
    bind("button.click", self.btn_stop_auto, self.stop_auto_ivk)

    self.press_auto_unbind = gamelib.utility.press_button(self.btn_launch.gameObject, function() self:auto_ivk() end, function() self:launch_ivk() end, 2)

    game.utility.button_style.highlight_scale(self.btn_launch)
    game.utility.button_style.highlight_scale(self.btn_stop_auto)
end

local function run(self)
    local amount = game.store.machine.getters.bet_value
    local player = game.kbe.player()
    if player and player.chip < amount then
        game.store.machine.on_auto(false)
        -- app.toast.show("没钱了~")
        -- TODO:弹出看广告/充值框
        return
    end
    self.systems:cleanup()
    if player and player.spin then
        player:spin(amount)
    end
    self.systems:execute()
end

function M:launch_ivk()
    if self.systems.current then
        self.systems.current:skip()
        return
    end

    run(self)
end

function M:auto_ivk()
    group = self.context:get_group(Matcher({components.auto_component}))
    group.entities:foreach(function(e)
        local c = e:get(components.auto_component)
        c.auto_func = function() run(self) end
    end)

    game.store.machine.on_auto(true)
    if self.systems.current == nil then
        self:launch_ivk()
    end

    app.audio.post("slotlib:auto_spin_1")
end

function M:stop_auto_ivk()
    game.store.machine.on_auto(false)
end

function M:on_release()
    self:super("on_release")
    if self.press_auto_unbind then
        self.press_auto_unbind()
    end
end

return M